<template>
  <div class="wardrobe">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-left">
        <h2>我的衣柜</h2>
        <p>管理你的所有衣物，让搭配更简单</p>
      </div>
      <div class="header-right">
        <el-button type="primary" @click="$router.push('/wardrobe/add')">
          <el-icon><Plus /></el-icon>
          添加衣服
        </el-button>
      </div>
    </div>

    <!-- 筛选和搜索 -->
    <el-card class="filter-card">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-input
            v-model="searchKeyword"
            placeholder="搜索衣服名称、品牌..."
            clearable
            @input="handleSearch"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-select v-model="filterCategory" placeholder="选择分类" clearable @change="handleFilter">
            <el-option label="全部分类" value="" />
            <el-option
              v-for="category in categories"
              :key="category.id"
              :label="category.name"
              :value="category.id"
            />
          </el-select>
        </el-col>
        <el-col :span="4">
          <el-select v-model="filterSeason" placeholder="选择季节" clearable @change="handleFilter">
            <el-option label="全部季节" value="" />
            <el-option label="春季" value="spring" />
            <el-option label="夏季" value="summer" />
            <el-option label="秋季" value="autumn" />
            <el-option label="冬季" value="winter" />
            <el-option label="四季" value="all" />
          </el-select>
        </el-col>
        <el-col :span="4">
          <el-select v-model="filterStatus" placeholder="选择状态" clearable @change="handleFilter">
            <el-option label="全部状态" value="" />
            <el-option label="可穿" value="available" />
            <el-option label="正在穿" value="wearing" />
            <el-option label="待洗" value="washing" />
            <el-option label="送洗" value="dry_cleaning" />
          </el-select>
        </el-col>
        <el-col :span="6">
          <div class="view-controls">
            <el-radio-group v-model="viewMode" @change="handleViewModeChange">
              <el-radio-button label="grid">
                <el-icon><Grid /></el-icon>
              </el-radio-button>
              <el-radio-button label="list">
                <el-icon><List /></el-icon>
              </el-radio-button>
            </el-radio-group>
            <el-switch
              v-model="showFavoriteOnly"
              active-text="仅收藏"
              @change="handleFilter"
            />
          </div>
        </el-col>
      </el-row>
    </el-card>

    <!-- 衣服列表 -->
    <div class="clothing-container" v-loading="loading">
      <!-- 网格视图 -->
      <div v-if="viewMode === 'grid'" class="grid-view">
        <div
          v-for="item in clothingList"
          :key="item.id"
          class="clothing-card"
          @click="viewClothingDetail(item.id)"
        >
          <div class="card-image">
            <el-image
              :src="item.images[0] || '/placeholder.jpg'"
              fit="cover"
              class="clothing-image"
            />
            <div class="card-overlay">
              <el-button-group>
                <el-button size="small" @click.stop="editClothing(item)">
                  <el-icon><Edit /></el-icon>
                </el-button>
                <el-button size="small" @click.stop="toggleFavorite(item)">
                  <el-icon><Star v-if="!item.is_favorite" /><StarFilled v-else /></el-icon>
                </el-button>
                <el-button size="small" type="danger" @click.stop="deleteClothing(item)">
                  <el-icon><Delete /></el-icon>
                </el-button>
              </el-button-group>
            </div>
            <div class="status-badge" :class="item.status">
              {{ getStatusText(item.status) }}
            </div>
          </div>
          <div class="card-content">
            <div class="clothing-name">{{ item.name }}</div>
            <div class="clothing-meta">
              <span class="brand">{{ item.brand || '未知品牌' }}</span>
              <span class="category">{{ getCategoryText(item.category_id) }}</span>
            </div>
            <div class="clothing-tags">
              <el-tag v-if="item.color" size="small" :color="item.color_hex">
                {{ item.color }}
              </el-tag>
              <el-tag v-if="item.season" size="small" type="info">
                {{ getSeasonText(item.season) }}
              </el-tag>
            </div>
          </div>
        </div>
      </div>

      <!-- 列表视图 -->
      <el-table v-else :data="clothingList" class="clothing-table">
        <el-table-column width="80">
          <template #default="{ row }">
            <el-image
              :src="row.main_image || '/placeholder.jpg'"
              fit="cover"
              class="table-image"
            />
          </template>
        </el-table-column>
        <el-table-column prop="name" label="名称" min-width="120" />
        <el-table-column prop="brand" label="品牌" width="100" />
        <el-table-column label="分类" width="100">
          <template #default="{ row }">
            {{ getCategoryText(row.category_id) }}
          </template>
        </el-table-column>
        <el-table-column prop="color" label="颜色" width="80" />
        <el-table-column label="季节" width="80">
          <template #default="{ row }">
            {{ getSeasonText(row.season) }}
          </template>
        </el-table-column>
        <el-table-column label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="wear_count" label="穿着次数" width="100" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button size="small" @click="viewClothingDetail(row.id)">查看</el-button>
            <el-button size="small" @click="editClothing(row)">编辑</el-button>
            <el-button size="small" @click="toggleFavorite(row)">
              {{ row.is_favorite ? '取消收藏' : '收藏' }}
            </el-button>
            <el-button size="small" type="danger" @click="deleteClothing(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :total="total"
        :page-sizes="[12, 24, 48, 96]"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { clothingAPI, categoryAPI } from '@/api'

// 路由实例
const router = useRouter()

// 响应式数据
const searchKeyword = ref('')
const filterCategory = ref('')
const filterSeason = ref('')
const filterStatus = ref('')
const showFavoriteOnly = ref(false)
const viewMode = ref('grid')
const currentPage = ref(1)
const pageSize = ref(24)
const total = ref(0)
const clothingList = ref([])
const loading = ref(false)
const categories = ref([])

// 加载分类列表
const loadCategories = async () => {
  try {
    const response = await categoryAPI.getList()
    if (response.code === 200) {
      categories.value = response.data || []
    }
  } catch (error) {
    console.error('获取分类列表失败:', error)
    // 使用默认分类作为后备
    categories.value = [
      { id: 1, name: '上装' },
      { id: 2, name: '下装' },
      { id: 3, name: '外套' },
      { id: 4, name: '鞋子' },
      { id: 5, name: '配饰' }
    ]
  }
}

// 加载衣服列表
const loadClothingList = async () => {
  try {
    loading.value = true

    const params = {
      page: currentPage.value,
      pageSize: pageSize.value,
      keyword: searchKeyword.value || undefined,
      category_id: filterCategory.value || undefined,
      season: filterSeason.value || undefined,
      status: filterStatus.value || undefined,
    }

    // 如果只显示收藏的
    if (showFavoriteOnly.value) {
      params.is_favorite = 'true'  // 确保传递字符串
    }

    const response = await clothingAPI.getList(params)

    // 处理响应数据结构
    if (response.code === 200) {
      clothingList.value = response.data.list || []
      total.value = response.data.total || 0
    } else {
      throw new Error(response.message || '获取数据失败')
    }

  } catch (error) {
    console.error('获取衣服列表失败:', error)
    ElMessage.error('获取衣服列表失败，请稍后重试')

    // 使用模拟数据作为后备
    clothingList.value = [
      {
        id: 1,
        name: '白色基础T恤',
        brand: 'UNIQLO',
        category: { name: 'T恤' },
        color: '白色',
        color_hex: '#FFFFFF',
        season: 'all',
        status: 'available',
        wear_count: 5,
        is_favorite: true,
        main_image: ''
      },
      {
        id: 2,
        name: '深蓝色直筒牛仔裤',
        brand: "Levi's",
        category: { name: '牛仔裤' },
        color: '深蓝色',
        color_hex: '#191970',
        season: 'all',
        status: 'available',
        wear_count: 15,
        is_favorite: true,
        main_image: ''
      }
    ]
    total.value = clothingList.value.length
  } finally {
    loading.value = false
  }
}

// 方法
const handleSearch = () => {
  currentPage.value = 1
  loadClothingList()
}

const handleFilter = () => {
  currentPage.value = 1
  loadClothingList()
}

const handleViewModeChange = () => {
  // 视图模式切换
}

const handleSizeChange = (size) => {
  pageSize.value = size
  loadClothingList()
}

const handleCurrentChange = (page) => {
  currentPage.value = page
  loadClothingList()
}

const viewClothingDetail = (id) => {
  // 跳转到详情页
  // router.push(`/wardrobe/${id}`)
}

const editClothing = (item) => {
  // 跳转到编辑页面
  router.push(`/clothing/${item.id}/edit`)
}

const toggleFavorite = async (item) => {
  try {
    await clothingAPI.toggleFavorite(item.id)
    item.is_favorite = !item.is_favorite
    ElMessage.success(item.is_favorite ? '已收藏' : '已取消收藏')
  } catch (error) {
    console.error('收藏操作失败:', error)
    ElMessage.error('操作失败，请稍后重试')
  }
}

const deleteClothing = (item) => {
  ElMessageBox.confirm('确定要删除这件衣服吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await clothingAPI.delete(item.id)
      ElMessage.success('删除成功')
      // 重新加载列表
      loadClothingList()
    } catch (error) {
      console.error('删除失败:', error)
      ElMessage.error('删除失败，请稍后重试')
    }
  }).catch(() => {
    // 用户取消删除
  })
}

// 辅助方法
const getCategoryText = (categoryId) => {
  // 如果有category对象，直接返回名称
  if (typeof categoryId === 'object' && categoryId?.name) {
    return categoryId.name
  }

  // 否则根据ID映射
  const categories = {
    1: '上装',
    2: '下装',
    3: '外套',
    4: '鞋子',
    5: '配饰',
    11: 'T恤',
    12: '衬衫',
    13: '毛衣',
    14: '背心',
    21: '牛仔裤',
    22: '休闲裤',
    23: '短裤',
    24: '裙子',
    31: '夹克',
    32: '大衣',
    33: '羽绒服',
    41: '运动鞋',
    42: '皮鞋',
    43: '靴子',
    51: '帽子',
    52: '包包',
    53: '首饰'
  }
  return categories[categoryId] || '未知'
}

const getSeasonText = (season) => {
  const seasons = {
    spring: '春季',
    summer: '夏季',
    autumn: '秋季',
    winter: '冬季',
    all: '四季'
  }
  return seasons[season] || '未知'
}

const getStatusText = (status) => {
  const statuses = {
    available: '可穿',
    wearing: '正在穿',
    washing: '待洗',
    dry_cleaning: '送洗',
    damaged: '损坏',
    donated: '已捐赠'
  }
  return statuses[status] || '未知'
}

const getStatusType = (status) => {
  const types = {
    available: 'success',
    wearing: 'warning',
    washing: 'info',
    dry_cleaning: 'info',
    damaged: 'danger',
    donated: 'info'
  }
  return types[status] || 'info'
}

onMounted(() => {
  loadCategories()
  loadClothingList()
})
</script>

<style scoped>
.wardrobe {
  width: 100%;
  height: 100%;
  padding: 0;
  overflow-y: auto;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header-left h2 {
  margin: 0 0 5px 0;
  color: #303133;
}

.header-left p {
  margin: 0;
  color: #606266;
  font-size: 14px;
}

.filter-card {
  margin-bottom: 20px;
}

.view-controls {
  display: flex;
  align-items: center;
  gap: 15px;
}

.clothing-container {
  margin-bottom: 20px;
}

.grid-view {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
  width: 100%;
}

.clothing-card {
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  overflow: hidden;
  cursor: pointer;
  transition: all 0.3s;
  flex: 0 0 calc(20% - 16px);
  min-width: 200px;
  max-width: 300px;
}

.clothing-card:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  transform: translateY(-2px);
}

.card-image {
  position: relative;
  height: 200px;
}

.clothing-image {
  width: 100%;
  height: 100%;
}

.card-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  opacity: 0;
  transition: opacity 0.3s;
}

.clothing-card:hover .card-overlay {
  opacity: 1;
}

.status-badge {
  position: absolute;
  top: 8px;
  right: 8px;
  padding: 2px 8px;
  border-radius: 12px;
  font-size: 12px;
  color: white;
  background: #909399;
}

.status-badge.available {
  background: #67c23a;
}

.status-badge.wearing {
  background: #e6a23c;
}

.card-content {
  padding: 15px;
}

.clothing-name {
  font-size: 16px;
  font-weight: 500;
  color: #303133;
  margin-bottom: 8px;
}

.clothing-meta {
  display: flex;
  justify-content: space-between;
  font-size: 12px;
  color: #909399;
  margin-bottom: 8px;
}

.clothing-tags {
  display: flex;
  gap: 5px;
  flex-wrap: wrap;
}

.table-image {
  width: 60px;
  height: 60px;
  border-radius: 4px;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

/* 响应式设计 */
@media (max-width: 1400px) {
  .clothing-card {
    flex: 0 0 calc(25% - 15px);
  }
}

@media (max-width: 1200px) {
  .clothing-card {
    flex: 0 0 calc(33.333% - 14px);
  }
}

@media (max-width: 900px) {
  .clothing-card {
    flex: 0 0 calc(50% - 10px);
  }
}

@media (max-width: 600px) {
  .clothing-card {
    flex: 0 0 100%;
    max-width: none;
  }

  .grid-view {
    gap: 15px;
  }
}
</style>
